from django import forms
from django.contrib.auth.models import User
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column, Field
from .models import SubProject
from apps.projects.models import Project
from apps.accounts.models import College


class SubProjectForm(forms.ModelForm):
    """子项目创建和编辑表单"""
    
    class Meta:
        model = SubProject
        fields = [
            'name', 'description', 'project', 'manager', 
            'team_members', 'college', 'project_start_date', 
            'midterm_check_date', 'project_end_date'
        ]
        widgets = {
            'description': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'team_members': forms.Textarea(attrs={'rows': 3, 'class': 'form-control', 'placeholder': '多个成员用逗号分隔'}),
            'project_start_date': forms.DateInput(attrs={
                'type': 'date',
                'class': 'form-control'
            }),
            'midterm_check_date': forms.DateInput(attrs={
                'type': 'date',
                'class': 'form-control'
            }),
            'project_end_date': forms.DateInput(attrs={
                'type': 'date',
                'class': 'form-control'
            }),
        }
        labels = {
            'name': '子项目名称',
            'description': '子项目描述',
            'project': '所属项目',
            'manager': '负责人',
            'team_members': '团队成员',
            'college': '所属二级学院',
            'project_start_date': '立项时间',
            'midterm_check_date': '中期检查时间',
            'project_end_date': '结项时间',
        }

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        project_id = kwargs.pop('project_id', None)
        is_edit = kwargs.pop('is_edit', False)
        super().__init__(*args, **kwargs)
        
        # 存储项目ID用于后续处理
        self.project_id = project_id
        
        # 如果指定了项目ID，则固定选择该项目且不允许修改
        if project_id:
            try:
                project = Project.objects.get(pk=project_id)
                self.fields['project'].initial = project
                self.fields['project'].queryset = Project.objects.filter(pk=project_id)
                self.fields['project'].widget.attrs['readonly'] = True
                self.fields['project'].widget.attrs['style'] = 'pointer-events: none; background-color: #e9ecef;'
            except Project.DoesNotExist:
                pass
        elif is_edit and self.instance.pk:
            # 编辑时也不允许修改所属项目
            self.fields['project'].queryset = Project.objects.filter(pk=self.instance.project.pk)
            self.fields['project'].widget.attrs['readonly'] = True
            self.fields['project'].widget.attrs['style'] = 'pointer-events: none; background-color: #e9ecef;'
        
        # 根据用户角色限制负责人选择和设置学院信息
        if user and hasattr(user, 'userprofile'):
            if user.userprofile.role == 'college':
                # 二级学院用户只能选择本学院的用户作为负责人
                college_users = User.objects.filter(
                    userprofile__college=user.userprofile.college
                )
                self.fields['manager'].queryset = college_users
                
                # 自动设置所属二级学院为当前用户的学院
                self.fields['college'].initial = user.userprofile.college
                # 对于二级学院用户，学院字段设为只读
                self.fields['college'].widget.attrs['disabled'] = True
            else:
                # 管理员可以手动选择学院
                pass
        
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('name', css_class='form-group mb-3'),
            Field('description', css_class='form-group mb-3'),
            Field('project', css_class='form-group mb-3'),
            Row(
                Column('manager', css_class='form-group col-md-6 mb-3'),
                Column('college', css_class='form-group col-md-6 mb-3'),
            ),
            Field('team_members', css_class='form-group mb-3'),
            Row(
                Column('project_start_date', css_class='form-group col-md-4 mb-3'),
                Column('midterm_check_date', css_class='form-group col-md-4 mb-3'),
                Column('project_end_date', css_class='form-group col-md-4 mb-3'),
            ),
            Submit('submit', '保存子项目', css_class='btn btn-primary')
        )

    def clean(self):
        cleaned_data = super().clean()
        
        # 如果是通过project_id创建，确保project字段被正确设置
        if hasattr(self, 'project_id') and self.project_id:
            try:
                project = Project.objects.get(pk=self.project_id)
                cleaned_data['project'] = project
            except Project.DoesNotExist:
                raise forms.ValidationError('指定的项目不存在')
        
        return cleaned_data


class SubProjectSearchForm(forms.Form):
    """子项目搜索表单"""
    
    search = forms.CharField(
        max_length=100, 
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': '搜索子项目名称或描述...',
            'class': 'form-control'
        }),
        label='搜索关键词'
    )
    
    status = forms.ChoiceField(
        choices=[('', '全部状态')] + SubProject.STATUS_CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='项目状态'
    )
    
    project = forms.ModelChoiceField(
        queryset=Project.objects.all(),
        required=False,
        empty_label='全部项目',
        widget=forms.Select(attrs={'class': 'form-control'}),
        label='所属项目'
    )

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # 根据用户角色限制项目选择
        if user and hasattr(user, 'userprofile'):
            if user.userprofile.role == 'college':
                # 二级学院用户只能看到相关项目
                self.fields['project'].queryset = Project.objects.filter(
                    admin_manager__userprofile__college=user.userprofile.college
                )
        
        self.helper = FormHelper()
        self.helper.form_method = 'get'
        self.helper.layout = Layout(
            Row(
                Column('search', css_class='form-group col-md-4 mb-3'),
                Column('status', css_class='form-group col-md-4 mb-3'),
                Column('project', css_class='form-group col-md-4 mb-3'),
            ),
            Submit('submit', '搜索', css_class='btn btn-outline-primary')
        )


class SubProjectStatusForm(forms.ModelForm):
    """子项目状态更新表单"""
    
    class Meta:
        model = SubProject
        fields = ['status']
        widgets = {
            'status': forms.Select(attrs={'class': 'form-control'}),
        }
        labels = {
            'status': '项目状态',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('status', css_class='form-group mb-3'),
            Submit('submit', '更新状态', css_class='btn btn-primary')
        )